package demo6;

import demo5.DescIntWritable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

public class Sort3Job {
    // 目标：默认排序
    public static void main(String[] args) throws Exception{
        // 1. 初始化配置
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://hadoop10:9000");
        //2. 创建job
        Job job = Job.getInstance(conf);
        job.setJarByClass(Sort3Job.class);

        //3. 设置输入(读取文件）和输出(输出计算结果)的类
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        //4. 设置输入路径和输出路径
        TextInputFormat.addInputPath(job, new Path("/mapreduce/demo6/sort3.txt"));
        TextOutputFormat.setOutputPath(job, new Path("/mapreduce/demo6/out"));

        //5. 设置mapper和reducer
        job.setMapperClass(Sort3Mapper.class);
        job.setReducerClass(Sart3Reducer.class);

        // 6. 设置mapper的kv类型和reducer的kv类型
        job.setMapOutputKeyClass(PlayWritable.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(PlayWritable.class);

        // 7. 启动job
        boolean b = job.waitForCompletion(true);
        System.out.println(b);

    }

    static class Sort3Mapper extends Mapper<LongWritable, Text, PlayWritable,Text>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            // 输入的 key    -  value
            //       偏移量  - 团团 300  1000
            String[] arr = value.toString().split("\t");
            context.write(new PlayWritable(Integer.parseInt(arr[1]),Integer.parseInt(arr[2])),new Text(arr[0]));
            // 输出的  key -     value
            //       300  1000  团团
        }
    }
    static class Sart3Reducer extends Reducer<PlayWritable,Text,Text,PlayWritable>{
        @Override
        protected void reduce(PlayWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            // 输入的 key - value
            //       100 - [卢本伟，悟空，唐曾]
            for (Text v : values){
                context.write(v,key);
            }
            // 输出的 key - value
            /*
            *        卢本伟 100
            *        悟空   100
            *        唐曾   100
            * */
        }
    }
}
